﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Collections;

namespace Facebook
{
    public static class Extensions
    {
        public static IDictionary<String, Object> SerializeToDictionary(this Object input)
        {
            var type = input.GetType();
            PropertyInfo[] properties = type.GetProperties();

            var result = properties.ToDictionary(propInfo => propInfo.Name, propInfo => propInfo.GetValue(input, null));
            return result;
        }

        public static Boolean TryMakeEnumerable(this Object input, out IEnumerable col)
        {
            var type = input.GetType();
            if (type == typeof(String))
            {
                col = null;
                return false;
            }
            else
            {
                col = input as IEnumerable;
                return col != null;
            }
        }

        public static String ToDelimitedString(this IEnumerable input, String delimiter)
        {
            return String.Join(delimiter, (
                from obj in input.OfType<Object>()
                select obj == null ? String.Empty : obj.ToString()).ToArray());
        }

        public static String ToDelimitedString(this IEnumerable input, Char delimiter)
        {
            return input.ToDelimitedString(delimiter.ToString());
        }

        public static String ToJson(this IEnumerable input)
        {
            return String.Format("[{0}]", String.Join(",", (
                from obj in input.OfType<Object>()
                select obj == null ? String.Empty : obj.ToString()).ToArray()));
        }
    }
}